<?php
/*
 +----------------------------------------------------------------------
 + Title        : WechatPayService 控制器
 + Author       : Randy_chen
 + Version      : V1.0.0.1
 + Initial-Time : 2023/5/15 23:54
 + Last-time    : 2023/5/15 23:54+ chen2
 + Desc         : WechatPayService
 +----------------------------------------------------------------------
*/


namespace app\user\service;

use EasyWeChat\Pay\Application;
use think\facade\Route;

class WechatPayService
{
    public static function getConfig() : array
    {
        return [
            'app_id'         => config("app.wechat.appid"),
            'mch_id'         => config("app.wechat.mch_id"),
            'secret_key'     => config("app.wechat.mch_key"), // 微信支付的KEY
            'private_key'    => __DIR__ . '/cert/apiclient_key.pem',
            'certificate'    => __DIR__ . '/cert/apiclient_cert.pem',
            'platform_certs' => [],
            'http'           => [
                'throw'   => true,
                'timeout' => 5.0,
            ],
        ];
    }

    public static function payService()
    {
        return new Application(self::getConfig());
    }

    /**
     * @param $sn
     * @param $title
     * @param $notify_url
     * @param $money
     * @param $openid
     *
     * @return mixed[]
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    public function createOrder($sn, $title, $notify_url, $money, $openid)
    {
        $payService = self::payService();
        $config = self::getConfig();
        $appId = $config['app_id'];
        $notify_url = Route::buildUrl($notify_url)
                           ->suffix('')
                           ->domain(true)
                           ->build();
        $post = [
            "mchid"        => $config['mch_id'],
            "out_trade_no" => $sn,//.'_'.randString(4),
            "appid"        => $appId,
            "description"  => $title,
            "notify_url"   => $notify_url,
            "amount"       => [
                "total"    => (int)bcmul($money, 100),
                "currency" => "CNY"
            ],
            "payer"        => [
                "openid" => $openid
            ]
        ];
        $res = $payService->getClient()
                          ->postJson("v3/pay/transactions/jsapi", $post)
                          ->toArray(false);
        if (isset($res['code'])) {
            error_abort($res['message']);
        }
        $prepayId = $res['prepay_id'];
        $signType = 'RSA';
        return $payService->getUtils()
                          ->buildMiniAppConfig($prepayId, $appId, $signType);
    }
}